package busi

import (
	"database/sql/driver"
	"fmt"
	htbsc "gitee.com/hangzhou_huitian/ht-basic/basic"
	"reflect"
	"time"
)

type Area struct {
	Name string `gorm:"column:area_name"`
	Code string `gorm:"column:area_code"`
}

type Patient struct {
	PatientId string   `gorm:"column:patient_id" json:"patientId"`
	InId      string   `gorm:"column:in_id" json:"inId"`
	Name      string   `gorm:"column:name" json:"name"`
	VisitNo   string   `gorm:"column:visit_no" json:"visitNo"`
	Gender    string   `gorm:"column:gender" json:"gender"`
	Age       string   `gorm:"column:age" json:"age"`
	Blood     string   `gorm:"column:blood" json:"blood"`
	Mobile    string   `gorm:"column:mobile" json:"mobile"`
	InDate    JsonTime `gorm:"column:in_date" json:"inDate"`
	Area      string   `gorm:"column:area" json:"area"`
	Bed       string   `gorm:"column:bed" json:"bed"`
	MiType    string   `gorm:"column:mi_type" json:"miType"`
}
type Order struct {
	htbsc.Order
	Scene      int
	Seq        int
	can_update int `gorm:"column:can_update"`
}
type OrderScene struct {
	Id            int    `gorm:"primary_key" json:"id"`
	Scene         int    `gorm:"column:scene" json:"scene"`
	OrderSeq      int    `gorm:"column:order_seq" json:"orderSeq"`
	VisitNo       string `gorm:"column:visit_no" json:"visitNo"`
	UpdatedOrders string `gorm:"column:updated_orders" json:"updatedOrders"`
}

type IfsInfo struct {
	Id      int    `gorm:"primary_key" `
	Request string `gorm:"column:request" `
}

func (IfsInfo) TableName() string {
	return "ifs_info"
}

type JsonTime time.Time

func (t JsonTime) MarshalJSON() ([]byte, error) {
	if &t == nil || time.Time(t).IsZero() {
		return []byte("null"), nil
	}
	var stamp = fmt.Sprintf("\"%s\"", time.Time(t).Format(time.DateTime))
	return []byte(stamp), nil
}

// Value insert timestamp into mysql need this function.
func (t JsonTime) Value() (driver.Value, error) {
	var zeroTime time.Time
	if time.Time(t).UnixNano() == zeroTime.UnixNano() {
		return nil, nil
	}
	return time.Time(t), nil
}

// Scan valueof time.Time
func (t *JsonTime) Scan(v interface{}) error {
	switch v.(type) {
	case []byte, string:
		var s string
		if reflect.TypeOf(v).Kind() == reflect.Slice {
			s = string(v.([]byte))
		} else {
			s = v.(string)
		}
		tm, err := time.ParseInLocation(time.DateTime, s, time.Local)
		if err == nil {
			*t = JsonTime(tm)
			return nil
		}
		return err
	case time.Time:
		value, _ := v.(time.Time)
		*t = JsonTime(value)
		return nil
	}
	return fmt.Errorf("can not convert %ov to timestamp", v)
}
